'''
Created on Apr 4, 2012

@author: Travis Elam

@author: Chase Knudson
 
@author: Mike Altreuter

@author: Jonny Hatch

'''
# System Requirements:
# Not a DELL
# Gymnastic Edit menu
#
# A program for scoring, editing, viewing,
# and printing gymnastic's meet results

from tkinter import *
from tkinter import ttk
import shelve, pprint, subprocess
import os
from operator import itemgetter
import re

# Teams List
teamlist = []
opened_file = []

# Makes dictionaries
class Teams():
    def __init__(self):
        self.teams = {}

    def create_team(self, team):
        """Don't make duplicate teams"""
        if not team in self.teams:
            self.teams[team] = {}

    def add_player(self, player, team):
        if not player in self.teams[team]:
            self.teams[team][player] = {"Vault":0,
                                        "Bars":0,
                                        "Beam":0,
                                        "Floor":0,
                                        "Penalty":0,
                                        "Total":0}
        
    def add_vault(self, vault, team, player):
        self.teams[team][player]["Vault"] = float(vault)
    def add_bars(self, bars, team, player):
        self.teams[team][player]["Bars"] = float(bars)
    def add_beam(self, beam, team, player):
        self.teams[team][player]["Beam"] = float(beam)
    def add_floor(self, floor, team, player):
        self.teams[team][player]["Floor"] = float(floor)
    def add_penalty(self, penalty, team, player):
        self.teams[team][player]["Penalty"] = penalty
    def add_total(self, total, team, player):
        self.teams[team][player]["Total"] = float(total)
        
    def print_to_file(self):
        team_str = ""
        width = "-"*100 + '\n' 
        columns = '|'
        for team, players in team_obj.teams.items():
            
            team_middle = int((100-len(team))/2)
            team_header = ' ' + width + ' |' + ' '*team_middle + team + ' '*(98-(team_middle+len(team))) + '|' +'\n' 
            tittles = '| '+"Team" + ' '*13 + "Gymnast" + ' '*15 + "Vault" + ' '*5 + "Beam" + ' '*5 + "Bars" + ' '*5 + "Floor" + ' '*5 + "Penalty" + ' '*5 + "Total" + ' '*3 + '|' 
            print(team_header, width, tittles, "\n", width)
            for player, scoredict in players.items():
                gymnast = player + '\n'
                scoredict["Vault"]
                print(" "*2+ player)
        
                      
    
team_obj = Teams()
teams = team_obj.teams   
team_totals = {}
all_arounds = Teams()   

def print_all_arounds():
    all_arounds_path = os.path.join(os.getcwd(), 'all_arounds.txt')
    for team, all in teams.items():
        team_all = team
        all_arounds.create_team(team_all)
        for player, score in all.items():
            current_player = player
            vault = score["Vault"]
            beam = score["Beam"]
            bars = score["Bars"]
            floor = score["Floor"]
            penalty = score["Penalty"]
            total = score["Total"]
            if vault and beam and bars and floor != 0:
                all_arounds.add_player(player, team_all)
                all_arounds.add_bars(bars, team_all, current_player)
                all_arounds.add_beam(beam, team_all, current_player)
                all_arounds.add_floor(floor, team_all, current_player)
                all_arounds.add_vault(vault, team_all, current_player)
                all_arounds.add_penalty(penalty, team_all, current_player)
                all_arounds.add_total(total, team_all, current_player)
    openText = open(all_arounds_path, 'w')
    pp = pprint.PrettyPrinter(indent=0, stream=openText)
    pp.pprint(all_arounds.teams)
    openText.close()
    subprocess.call(['notepad', all_arounds_path])     
    print(all_arounds.teams)
    
def print_top_players():
    topplayers_path = os.path.join(os.getcwd(), 'top_players.txt')
    global top_playas
    top_playas = []
    for team, all in teams.items():
        tops = team
        tops = {}
        for player, scores in all.items():
            all_things = teams[team][player]["Total"]
            tops[player] = all_things
            final = sorted(tops.items(), key=itemgetter(1), reverse = True)
        first, second, third, fourth = None, None, None, None
        try:
            first = final[0]
            second = final[1]
            third = final[2]
            fourth = final[3]
        except IndexError:
            pass
        top_four = {}
        top_four[team] = first, second, third, fourth
        top_playas.append(top_four)
    openText = open(topplayers_path, 'w')
    pp = pprint.PrettyPrinter(indent=0, stream=openText)
    pp.pprint(top_playas)
    openText.close()
    subprocess.call(['notepad', topplayers_path])
                  
def team_scores():
    team_sb = Toplevel()
    team_sb.title("Team Scores")
    team_sb.geometry ("312x200")
    team_sb.resizable(FALSE,FALSE)
    team_sb.configure(background="#800000")
    
    number_line = Listbox(team_sb,height=13,width=5)
    number_line.pack(side=LEFT)
    number_line.insert(END, "1 :","2 :","3 :","4 :","5 :","6 :","7 :","8 :","9 :","10 :")
    
    top_tb = Listbox(team_sb,height=13, width=30)
    top_tb.pack(side=LEFT)
    
    top_ts = Listbox(team_sb, height=13,width=15)
    top_ts.pack(side=LEFT)
    
    # Top teams  
    for team, all in teams.items():
        team_tops = team
        team_tops = {}
        for player, scores in all.items():
            all_things = teams[team][player]["Total"]
            team_tops[player] = all_things
            final = sorted(team_tops.items(), key=itemgetter(1), reverse = True)
        final_first = (0)
        final_second = (0)
        final_third = (0)
        final_fourth = (0)
        
        try:
            first = final[0]
            final_first = first[1]
            second = final[1]
            final_second = second[1]
            third = final[2]
            final_third = third[1]
            fourth = final[3]
            final_fourth = fourth[1]
        except IndexError:
            pass
        
        team_total = final_first + final_second + final_third + final_fourth
        team_totals[team] = team_total
        global top_teams
        top_teams = sorted(team_totals.items(), key=itemgetter(1))
    for key, value in top_teams:
            top_tb.insert(0,key)
            top_ts.insert(0,value)
        
def print_top_teams():
    topteams_path = os.path.join(os.getcwd(), 'top_teams.txt')
    for team, all in teams.items():
        team_tops = team
        team_tops = {}
        for player, scores in all.items():
            all_things = teams[team][player]["Total"]
            team_tops[player] = all_things
            final = sorted(team_tops.items(), key=itemgetter(1), reverse = True)
        final_first = (0)
        final_second = (0)
        final_third = (0)
        final_fourth = (0)
        
        try:
            first = final[0]
            final_first = first[1]
            second = final[1]
            final_second = second[1]
            third = final[2]
            final_third = third[1]
            fourth = final[3]
            final_fourth = fourth[1]
        except IndexError:
            pass
        
        team_total = final_first + final_second + final_third + final_fourth
        team_totals[team] = team_total
        global top_teams
        top_teams = sorted(team_totals.items(), key=itemgetter(1))
    
    openText = open(topteams_path, 'w')
    pp = pprint.PrettyPrinter(indent=0, stream=openText,width=25)
    pp.pprint(top_teams)
    openText.close()
    subprocess.call(['notepad', topteams_path])
 
# Makes teams clickable
def get_list(event):
    global seltext
    index = teambox.curselection()[0]
    seltext = teambox.get(index)
    teams_entry.delete(0, END)
    teams_entry.insert(0, seltext)
    playerbox.delete(0, 50)
    for key in teams[seltext]:
        playerbox.insert(0, key)
        vaultevent.delete(0, 50)
        beamevent.delete(0, 50)
        barsevent.delete(0, 50)
        floorevent.delete(0, 50)
        penbox.delete(0,50)
        totalbox.delete(0, 50)
        for value in teams[seltext]:
            vaultevent.insert(0, teams[seltext][value]["Vault"])
            beamevent.insert(0, teams[seltext][value]["Beam"])
            barsevent.insert(0, teams[seltext][value]["Bars"])
            floorevent.insert(0, teams[seltext][value]["Floor"])
            penbox.insert(0, teams[seltext][value]["Penalty"])
            totalbox.insert(0, str(int(teams[seltext][value]["Vault"]) 
                                              + float(teams[seltext][value]["Beam"]) 
                                              + float(teams[seltext][value]["Bars"]) 
                                              +  float(teams[seltext][value]["Floor"])
                                              - float(teams[seltext][value]["Penalty"])))      

def edit_player(event):
    global seltext1
    index = playerbox.curselection()[0]
    seltext1 = playerbox.get(index)
    players.delete(0, END)
    players.insert(0, seltext1)

    vault.delete(0, END)
    vault2.delete(0, END)
    beam.delete(0, END)
    beam2.delete(0, END)
    bars.delete(0, END)
    bars2.delete(0, END)
    floor.delete(0, END)
    floor2.delete(0, END)
    vault.insert(0, teams[seltext][seltext1]["Vault"])
    vault2.insert(0, teams[seltext][seltext1]["Vault"])
    beam.insert(0, teams[seltext][seltext1]["Beam"])
    beam2.insert(0, teams[seltext][seltext1]["Beam"])
    bars.insert(0, teams[seltext][seltext1]["Bars"])
    bars2.insert(0, teams[seltext][seltext1]["Bars"])
    floor.insert(0, teams[seltext][seltext1]["Floor"])
    floor2.insert(0, teams[seltext][seltext1]["Floor"])    
def edit_scores(event):
    index = playerbox.curselection()[0]
    seltext = playerbox.get(index)
    for key in teams[seltext]:
        print(key)


    vault.delete(0,END)
    vault.insert(0, teams[seltext][seltext1]["Vault"])
    vault2.delete(0,END)
    vault2.insert(0, teams[seltext][seltext1]["Vault"])
    beam.delete(0,END)
    beam.insert(0, teams[seltext][seltext1]["Beam"])
    beam2.delete(0,END)
    beam2.insert(0, teams[seltext][seltext1]["Beam"])
    bars.delete(0,END)
    bars.insert(0, teams[seltext][seltext1]["Bars"])
    bars2.delete(0,END)
    bars2.insert(0, teams[seltext][seltext1]["Bars"])
    floor.delete(0,END)
    floor.insert(0, teams[seltext][seltext1]["Floor"])
    floor2.delete(0,END)
    floor2.insert(0, teams[seltext][seltext1]["Floor"])                       
def print_pretty(event=None):
    team_obj.print_to_file()
    scores_path = os.path.join(os.getcwd(), 'scores.txt')
    openText = open(scores_path, 'w')
    pp = pprint.PrettyPrinter(indent=2, stream=openText, width=150)
    pp.pprint(teams)
    openText.close()
    subprocess.call(['notepad', scores_path])
    
# binds scrollbar to all event listboxes
def OnVsb(*args):
        vaultevent.yview(*args)
        beamevent.yview(*args)
        floorevent.yview(*args)
        barsevent.yview(*args)

# deletes players in listbox
def delete_item():
    """
    delete a selected line from the listbox
    """
    try:
        # get selected line index
        index = playerbox.curselection()[0]
        playerbox.delete(index)
    except IndexError:
        pass

# sorts players in listbox    
def sortplayer_list():
    """
    function to sort listbox items case insensitive
    """
    for team, value in teams.items():
        sorted_players = team
        sorted_players = sorted(teams[team])
        for player in sorted_players:
            playerbox.delete(0, END)
            vaultevent.delete(0, END)
            beamevent.delete(0, END)
            barsevent.delete(0, END)
            floorevent.delete(0, END)
            playerbox.insert(0, player)
            penbox.delete(0, END)
            totalbox.delete(0, END)
            vaultevent.insert(0, teams[team][player]["Vault"])
            barsevent.insert(0, teams[team][player]["Bars"])
            floorevent.insert(0, teams[team][player]["Floor"])
            beamevent.insert(0, teams[team][player]["Beam"])
            penbox.insert(0, teams[team][player]["Penalty"])
            totalbox.insert(0, teams[team][player]["Total"])
            beamevent.insert(0, teams[team][player]["Beam"])     

    
#    temp_list = list(playerbox.get(0, END))
#    temp_list.sort(key=str.lower)
#    # delete contents of present listbox
#    playerbox.delete(0, END)
#    # load listbox with sorted data
#    for item in temp_list:
#        playerbox.insert(END, item)

# sorts teams in listbox
def sortteam_list():
    """
    function to sort listbox items case insensitive
    """
    temp_list1 = list(teambox.get(0, END))
    temp_list1.sort(key=str.lower)
    # delete contents of present listbox
    teambox.delete(0, END)
    # load listbox with sorted data
    for item in temp_list1:
        teambox.insert(END, item)

# pop-up window for credits
def credit_box():
    # frame inside box
    credit = Toplevel()
    credit.geometry("503x504")
    credit.focus()
    credit.title("CREDITS")
    credit.resizable(FALSE,FALSE)
    credit.configure(background="#800000")
    # picture
    dev = PhotoImage(file='Credits.gif')
    pic6 = Label(credit, image=dev, width=479, height=479, relief=RIDGE)
    pic6.photo = dev
    pic6.place(x=10, y=10)
    
file_list = []   

def add_roster(event=None):
    roster = Toplevel()
    roster.geometry("200x175")
    roster.focus()
    roster.title("Add A Roster")
    roster.resizable(FALSE, FALSE)
    roster.configure(background="#800000")
    
    team_lbl = Label(roster, text="Team  Name", width=20, fg='white', bg='black', relief=RIDGE)
    team_lbl.place(x=28 , y=5)

    global new_team
    new_team = Entry(roster, width=23, justify=CENTER, relief=RIDGE)
    new_team.place(x=30, y=30)
    new_team.focus_set()
    
    player_lbl = Label(roster, text="Gymnast  Name", width=20, fg='white', bg='black', relief=RIDGE)
    player_lbl.place(x=29, y=70)
    
    global new_player
    asdf = StringVar()
    new_player = ttk.Entry(roster, textvariable=asdf, width=23, justify=CENTER)
    new_player.place(x=30, y=95)
    
    add_bttn = Button(roster, bg='white', fg='black', text="SUBMIT", width=15, command=submit_roster, relief=RIDGE)
    add_bttn.place(x=43, y=135)
    roster.bind('<Return>', submit_roster)

def submit_roster(event=None):
    team_get = (new_team.get())
    player_get = (new_player.get())
    if team_get not in teamlist:
        teamlist.append(team_get)
        team_obj.create_team(team_get)
        teambox.insert(0, team_get)
    team_obj.add_player(player_get, team_get)
    new_player.delete(0, END)
    playerbox.insert(0, player_get)

# select and open a file    
def open_a_file(event=None):
    global open_file
    open_file = Toplevel()
    open_file.geometry("200x290")
    open_file.focus()
    open_file.title("Open File. . .")
    open_file.resizable(FALSE, FALSE)
    open_file.configure(background="black")
   
    global openbox            
    open_fr = Frame(open_file)
    open_fr.place(x=0,y=0)
    openlabel = Label(open_fr, text="F I L E S", fg='white', bg='black', relief=RIDGE)
    openlabel.pack(side=TOP,fill=X)
    openbox = Listbox(open_fr,background='white', width=30, height=15)
    openbox.pack(side=LEFT)
    open_sc = Scrollbar(open_fr, orient="vertical", command=openbox.yview)
    open_sc.pack(side=RIGHT, fill=Y)
    open_bttn = Button(open_file, text="O P E N", width=27, bg='white', fg='black', relief=RIDGE, command=open_thing)
    open_bttn.pack(side=BOTTOM,fill=X)
    openbox.bind('<Double-1>', open_thing)
     
    # Puts all saved files in listbox
    z = shelve.open('gymnastics_files.dat')
    for items in z:
        openbox.insert(0, items)
        z.close()

def open_thing(event=None):
    index = openbox.curselection()[0]
    seltext = openbox.get(index)
    s = shelve.open(seltext)
    open_file.destroy()
    opened_file.append(seltext)
    global teams
    teams = team_obj.teams = s['teams']
    for team in teams:
        if team not in teamlist:
            teamlist.append(team)
        teambox.insert(0, team)
        
        for player in team_obj.teams[team]:
            playerbox.insert(0,player)
            
            openVault = team_obj.teams[team][player]['Vault']
            vaultevent.insert(0, openVault)

            openBars = team_obj.teams[team][player]['Bars']
            barsevent.insert(0, openBars)            
            
            openBeam = team_obj.teams[team][player]['Beam']
            beamevent.insert(0, openBeam)            
            
            openFloor = team_obj.teams[team][player]['Floor']
            floorevent.insert(0, openFloor)
            
            openPen = team_obj.teams[team][player]['Penalty']
            penbox.insert(0, openPen)
            
            openTotal = team_obj.teams[team][player]['Total']
            totalbox.insert(0, openTotal)
            
    return teams
            
    s.close()

def save(event=None):
    for i in opened_file:
        file_name = i 
        s = shelve.open((file_name), 'c')
        s['teams'] = team_obj.teams
        s.sync()
        s.close()
        
def shelve_save(event=None):
    file_name = save_ent.get()
    s = shelve.open((file_name), 'c')
    s['teams'] = team_obj.teams
    s.sync()
    s.close()
    save_as.destroy()
    file_list.append(file_name)
    z = shelve.open('gymnastics_files.dat', 'c')
    z[file_name] = (file_name)
    z.sync()
    s.close()
        
def save_window(event=None):
    global save_as
    global save_ent

    global save_as    

    save_as = Toplevel()
    save_as.geometry("200x100")
    save_as.focus()
    save_as.title("Save As")
    save_as.resizable(FALSE,FALSE)
    save_as.configure(background="#800000")
    
    save_msg = Label(save_as, text="Save your file as . . .", width=20, bg="black", fg='white',relief=RIDGE)
    save_msg.place(x=26, y=5)
    
    global save_ent
    save_ent = Entry(save_as, width=23, justify=CENTER)
    save_ent.place(x=28, y=30)
    save_ent.bind('<Return>', shelve_save)
    save_ent.focus_set()
    
    save_bttn = Button(save_as, bg='white', fg='black', text="SAVE", width=10)
    save_bttn.place(x=58, y=60)
    save_bttn['command']= shelve_save
    save_bttn.bind('<Return>', shelve_save)
    
    for i in opened_file:
        save_ent.insert(0, i)

# pop-up window for instructions
def about_box():
    # frame inside box
    about = Toplevel()
    aboutfr = Frame(about, width=580, height=480, relief=RIDGE)
    aboutfr.place(x=10, y=10)
    about.geometry("608x504")
    about.focus()
    about.title("INSTRUCTIONS")
    about.resizable(FALSE,FALSE)
    about.configure(background="#800000")
    
    # create text box
    scrollbar = Scrollbar(aboutfr)
    scrollbar.pack(side=RIGHT, fill=Y)
    atext = Text(aboutfr, width=71, height=30, relief=RIDGE, wrap=WORD, yscrollcommand=scrollbar.set)
    atext.focus()
    atext.pack(side=LEFT)
    scrollbar.config(command=atext.yview)

    # instructions for text box
    atext.insert(END, """=======================================================================
----------------------------| DESCRIPTION |----------------------------
=======================================================================

Welcome to the Gymnastics program created by [T3AM S1LV3R BAX]. This program was created exclusively for the Holmen Gymnastics team. This program provides an easy, no-nonsense way for coaches, staff and players to efficiently record, view, save, and edit statistics for team members season after season.

=======================================================================
----------------------------| INSTRUCTIONS |---------------------------
=======================================================================

TO ENTER A TEAM:

In order to enter a new team into the program click in the text box adjacent to the 'Enter Team' label. Next, enter the name of the team you would like to add. Make sure to check the spelling. When finished, click the 'SUBMIT' button. The name should now appear in the 'TEAMS' category below. 

=======================================================================

TO DELETE A TEAM:

In order to delete a team name click on the name of the team listed under the 'TEAMS' category. When it is highlighted, click the 'DELETE' button below. 

=======================================================================

TO ENTER A GYMNAST:

To enter a gymnast into the program click in the text box adjacent to the 'Enter Gymnast' label Next, enter the name of the gymnast you would like to add. Make sure to check the spelling. When finished, click the 'SUBMIT' button. the name should now appear in the 'GYMNASTS' category below. 

=======================================================================

TO DELETE A GYMNAST:

In order to delete a gymnast name click on the name of the gymnast under the 'GYMNASTS' category. When it is highlighted, click the 'DELETE' button below.

=======================================================================

TO ENTER A SCORE FOR A NEW GYMNAST:

Enter the name of the school that you would like to add a gymnast to. Next, click in the text box adjacent to the 'Enter Gymnast' and enter the gymnast's name. Then enter the score for the event that you would like to add. You can add more than one event at a time. 

=======================================================================

TO ENTER A GYMNAST TO A PRE-EXISTING TEAM:

Click on the name of the team that you would like to  add a gymnast to. Then, click the 'EDIT' button and add the name of the gymnast. Click 'Enter' and you're done.

=======================================================================

TO ENTER A SCORE FOR A PRE-EXISTING GYMNAST:

Click the name of the gymnast listed under the 'GYMNASTS' category. Next, click the 'EDIT' button below. Enter the score for the event that you would like to add. There is no need to re-enter the gymnast in the entry boxes above. 

=======================================================================

TO SORT THE ORDER OF GYMNASTS IN A TEAM ALPHABETICALLY:

Click on the name of the team that you would like to sort. Once highlighted, click on the 'SORT' button below. 

=======================================================================

TO SAVE INFORMATION THAT HAS BEEN ENTERED:

When you are done entering all the information you want to add click the 'SAVE' button below. 

=======================================================================
|---------------------------------------------------------------------|
|---------------------------[ T3AM S1LV3R BAX ]-----------------------|
|---------------------------------------------------------------------|
|---------------------------[ Copyright 2012 ]------------------------|
|---------------------------------------------------------------------|
=======================================================================
""")
    atext.config(state=DISABLED)

def submit(event = NONE): 

    # get user input
    team_get = (teams_entry.get())
    player_get = (players.get())
    
    vault_get = (vault.get())
    vault_get2 = (vault2.get())

    beam_get = (beam.get())
    beam_get2 = (beam2.get())
    
    bars_get = (bars.get())
    bars_get2 = (bars2.get())
    
    floor_get = (floor.get())
    floor_get2 = (floor2.get())   
    
    # changing strings to float
    if vault_get == "":
        vault_int = 0
    else:
        vault_int = float(vault_get)
        
    if beam_get == "":
        beam_int = 0
    else:
        beam_int = float(beam_get)
        
    if bars_get == "":
        bars_int = 0
    else:
        bars_int = float(bars_get)
        
    if floor_get == "":
        floor_int = 0
    else:
        floor_int = float(floor_get)
  
        # changing strings to float
    if vault_get2 == "":
        vault_int2 = 0
    else:
        vault_int2 = float(vault_get2)
        
    if beam_get2 == "":
        beam_int2 = 0
    else:
        beam_int2 = float(beam_get2)
        
    if bars_get2 == "":
        bars_int2 = 0
    else:
        bars_int2 = float(bars_get2)
        
    if floor_get2 == "":
        floor_int2 = 0
    else:
        floor_int2 = float(floor_get2)
    
    vault_avg = ((vault_int+vault_int2)/2)
    bars_avg = ((bars_int+bars_int2)/2)
    beam_avg = ((beam_int+beam_int2)/2)
    floor_avg = ((floor_int+floor_int2)/2)
    
    penalty1_str = penalty1.get()
    penalty2_str = penalty2.get()
    penalty3_str = penalty3.get()
    penalty4_str = penalty4.get()
    
    
    if penalty1_str == "":
        penalty1_int = float(0)
    else:
        penalty1_int = float(penalty1_str) #vault
    
    if penalty2_str == "":
        penalty2_int = 0
    else:
        penalty2_int = float(penalty2_str) #beam
        
    if penalty3_str == "":
        penalty3_int = 0
    else:
        penalty3_int = float(penalty3_str) #bars
        
    if penalty4_str == "":
        penalty4_int = 0
    else:
        penalty4_int = float(penalty4_str) #floor    
        
    vault_total = vault_avg - penalty1_int
    beam_total = beam_avg - penalty2_int
    bars_total = bars_avg - penalty3_int
    floor_total = floor_avg - penalty4_int
    
    vault_str = str(vault_total)
    beam_str = str(beam_total)
    bars_str = str(bars_total)
    floor_str = str(floor_total)
    pen_str = (penalty1_int+penalty2_int+penalty3_int+penalty4_int) #total penalties

    
    # changes user input into intergers for adding
    scoretotal = float(vault_total + beam_total + bars_total + floor_total)
    
    # changes user input total back into strin
    if team_get not in teamlist:
        teambox.insert(0, team_get)
        teams_entry.delete(0, END)
        teamlist.append(team_get)

        team_obj.create_team(team_get)
    
    playerbox.insert(END, players.get())
    players.get()
    players.delete(0, END)
    if player_get not in team_obj.teams:
        team_obj.add_player(player_get, team_get)
    
    # place user input into appropriate boxes
    if vault_avg == 0:
        vaultevent.insert(END, 0)   
    else:
        vaultevent.insert(END, vault_str)
        team_obj.add_vault(vault_total, team_get, player_get)
        
    if beam_avg == 0:
        beamevent.insert(END, 0)    
    else:
        beamevent.insert(END, beam_str)
        team_obj.add_beam(beam_total, team_get, player_get)

    if floor_avg == 0:
        floorevent.insert(END, 0)
    else:
        floorevent.insert(END, floor_str)
        team_obj.add_floor(floor_total, team_get, player_get)

    if bars_avg == 0:
        barsevent.insert(END, 0)
    else:
        barsevent.insert(END, bars_str)
        team_obj.add_bars(bars_total, team_get, player_get) 

    penbox.insert(END, pen_str)
    team_obj.add_penalty(pen_str, team_get, player_get)

    totalbox.insert(END, scoretotal)
    team_obj.add_total(scoretotal, team_get, player_get)  

    teams_entry.delete(0, END)
    vault.delete(0, END)
    beam.delete(0, END)
    floor.delete(0, END)
    bars.delete(0, END)

    vault2.delete(0, END)
    beam2.delete(0, END)
    floor2.delete(0, END)
    bars2.delete(0, END)
    
    penalty1.delete(0, END)
    penalty2.delete(0, END)
    penalty3.delete(0, END)
    penalty4.delete(0, END) 
    
def close_program(event = None):
    root.destroy()

# create main window
root = Tk()
root.title("GYMNASTICS")
root.geometry ("775x535")
root.resizable(FALSE,FALSE)
root.configure(background="#800000")

# MenuBar
menubar = Menu(root)

# creates file menu
filemenu = Menu(menubar, tearoff=0)
printmenu = Menu(filemenu)
filemenu.add_command(label="Open", command=open_a_file, accelerator="Ctrl+O")
filemenu.add_command(label="Save", command=save, accelerator="Ctrl+S")
filemenu.add_command(label="Save As...", command=save_window)
filemenu.add_separator()
filemenu.add_cascade(label="Print", menu=printmenu)
printmenu.add_command(label="Meet Results", command=print_pretty, accelerator="Ctrl+P")
printmenu.add_command(label="Top 4 Players", command=print_top_players)
printmenu.add_command(label="Top 4 Teams", command=print_top_teams)
printmenu.add_command(label="All Arounds", command=print_all_arounds)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.destroy, accelerator="Ctrl+Q")
menubar.add_cascade(label="File", menu=filemenu)
filemenu.bind_all('<Control-s>', save)
filemenu.bind_all('<Control-q>', close_program)
filemenu.bind_all('<Control-o>', open_a_file)
printmenu.bind_all('<Control-p>',print_pretty)

# creates edit menu
editmenu = Menu(menubar, tearoff=0)
submenu = Menu(editmenu)
editmenu.add_cascade(label="Sort...", menu=submenu)
editmenu.add_cascade(label="Show All")
submenu.add_command(label="Teams", command=sortteam_list)
submenu.add_command(label="Players", command=sortplayer_list)   

menubar.add_cascade(label="Edit", menu=editmenu)

# creates help menu
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="About", command=about_box)
helpmenu.add_command(label="Credits", command=credit_box)
menubar.add_cascade(label="Help", menu=helpmenu)

# Add Roster
addmenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="Add Roster", command=add_roster)

# team scores
teammenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="|     Team Scores     |", command=team_scores)
teammenu.bind_all('<Control-a>', add_roster)

# pictures
viking = PhotoImage(file='viking.gif')
gymna = PhotoImage(file='gymnastics.gif')
gymtitle = PhotoImage(file='gymtitle.gif')

# Labels to insert pictures into
pic1 = Label(image=viking, height=115, width=480)
pic1.place(x=300)

pic2 = Label(image=gymna, height=100, width=148)
pic2.place(x=310, y=105)

pic3 = Label(image=gymtitle, height=70, width=270)
pic3.place(x=480, y=150)

# teams frame
teamfr=Frame()
teamlabel = Label(teamfr, text="T E A M S", fg='white', bg='black', width=18, relief=RIDGE)
teamlabel.pack(fill=X)
teambox = Listbox(teamfr,height=16,width=20,background='white')
teamfr.place(x=5, y=250)


# put a scroll bar in the teams frame
scroll1=Scrollbar(teamfr)
teambox.configure(yscrollcommand=scroll1.set)
        
# pack everything
teambox.pack(side=LEFT)
scroll1.pack(side=RIGHT,fill=Y)

# player frame
playerfr=Frame()
playerlabel = Label(playerfr, text="G Y M N A S T S", fg='white', bg='black', width=27, relief=RIDGE)
playerlabel.pack(fill=X)

playerbox = Listbox(playerfr,height=16,width=30,background='white')
playerfr.place(x=150, y=250)
        
# put a scroll bar in the player frame
scroll2=Scrollbar(playerfr)
playerbox.configure(yscrollcommand=scroll2.set)
        
# pack everything
playerbox.pack(side=LEFT)
scroll2.pack(side=RIGHT,fill=Y)

# event frame
eventfr=Frame()

# put a scroll bar in the event frame
vsb = Scrollbar(eventfr, orient="vertical", command=OnVsb)

# event listboxes 
eventlabel = Label(eventfr, text="   VAULT    |    BEAM      |     BARS      |    FLOOR    |  PENALTY  |      TOTAL          ",\
                    fg='white', bg='black', width=44, relief=RIDGE)
eventlabel.pack(fill=X)

vaultevent = Listbox(eventfr,height=16,width=10,background='white', yscrollcommand=vsb.set)
beamevent = Listbox(eventfr,height=16,width=10,background='white', yscrollcommand=vsb.set)
barsevent = Listbox(eventfr,height=16,width=10,background='white', yscrollcommand=vsb.set)
floorevent = Listbox(eventfr,height=16,width=10,background='white', yscrollcommand=vsb.set)
penbox = Listbox(eventfr,height=16,width=10,background='white', yscrollcommand=vsb.set)
totalbox = Listbox(eventfr,height=16,width=12,background='white', yscrollcommand=vsb.set)

eventfr.place(x=355, y=250)

# pack events and scrollbar
vaultevent.pack(side=LEFT)
beamevent.pack(side=LEFT)
barsevent.pack(side=LEFT)
floorevent.pack(side=LEFT)
penbox.pack(side=LEFT)
totalbox.pack(side=LEFT)
vsb.pack(side=RIGHT,fill=Y)

# variables for entry boxes
t = StringVar()
p = StringVar()
vv = StringVar()
b = StringVar()
f = StringVar()
ba = StringVar()
v2 = StringVar()
b2 = StringVar()
f2 = StringVar()
ba2 = StringVar()
penvar1 = StringVar()
penvar2 = StringVar()
penvar3 = StringVar()
penvar4 = StringVar()
AA = IntVar()

# labels for entry teams, gymnasts, and score

lbl1 = Label(root, text="Team  Name : ", width=15, fg='white', bg='black', relief=RIDGE)
lbl1.place(x=5 , y=5)

lbl2 = Label(root, text="Gymnast  Name : ", width=15, fg='white', bg='black', relief=RIDGE)
lbl2.place(x=5, y=30)

lbl3 = Label(root, text="Vault Score : ", width=10, fg='white', bg='black', relief=RIDGE)
lbl3.place(x=5 , y=85)

lbl4 = Label(root, text="Beam Score : ", width=10, fg='white', bg='black', relief=RIDGE)
lbl4.place(x=5 , y=110)

lbl5 = Label(root, text="Floor Score : ", width=10, fg='white', bg='black', relief=RIDGE)
lbl5.place(x=5 , y=160)

lbl6 = Label(root, text="Bars Score : ", width=10, fg='white', bg='black',relief=RIDGE)
lbl6.place(x=5 , y=135)

lbl8 = Label(root, text="Penalty", width=6, fg='white', bg='black', relief=RIDGE)
lbl8.place(x=200, y=60)

lbl9 = Label(root, text="Judge 1", width=6, fg='white', bg='black', relief=RIDGE)
lbl9.place(x=90, y=60)

lbl10 = Label(root, text="Judge 2", width=6, fg='white', bg='black', relief=RIDGE)
lbl10.place(x=145, y=60)

# entry boxes for team, gymnast, and scores
teams_entry = ttk.Entry(root, textvariable=t, width=18, justify=CENTER)
teams_entry.place(x=120, y=5)

# gymnast
players = ttk.Entry(root, textvariable=p, width=18, justify=CENTER)
players.place(x=120, y=30)

# vault
vault = ttk.Entry(root, textvariable=vv, width=7, justify=CENTER)
vault.place(x=90, y=85)

vault2 = ttk.Entry(root, textvariable=v2, width=7, justify=CENTER)
vault2.place(x=145, y=85)

penalty1 = ttk.Entry(root, textvariable=penvar1, width=7, justify=CENTER)
penalty1.place(x=200, y=85)
penalty1.bind('<Return>',submit)

# beam
beam = ttk.Entry(root, textvariable=b, width=7, justify=CENTER)
beam.place(x=90, y=110)

beam2 = ttk.Entry(root, textvariable=b2, width=7, justify=CENTER)
beam2.place(x=145, y=110)

penalty2 = ttk.Entry(root, textvariable=penvar2, width=7, justify=CENTER)
penalty2.place(x=200, y=110)
penalty2.bind('<Return>',submit)

# bars
bars = ttk.Entry(root, textvariable=ba, width=7, justify=CENTER)
bars.place(x=90, y=135)

bars2 = ttk.Entry(root, textvariable=ba2, width=7, justify=CENTER)
bars2.place(x=145, y=135)

penalty3 = ttk.Entry(root, textvariable=penvar3, width=7, justify=CENTER)
penalty3.place(x=200, y=135)
penalty3.bind('<Return>',submit)

# floor
floor = ttk.Entry(root, textvariable=f, width=7, justify=CENTER)
floor.place(x=90, y=160)

floor2 = ttk.Entry(root, textvariable=f2, width=7, justify=CENTER)
floor2.place(x=145, y=160)

penalty4 = ttk.Entry(root, textvariable=penvar4, width=7, justify=CENTER)
penalty4.place(x=200, y=160)
penalty4.bind('<Return>',submit)

# submit button
bttn1 = Button(root, text="SUBMIT",font='impact', width=15, relief=RAISED, command=submit)
bttn1.configure(background='white')
bttn1.bind('<Return>',submit)
bttn1.place(x=70, y=200)

# left mouse click on a list item to display selection
teambox.bind('<ButtonRelease-1>', get_list)
playerbox.bind('<ButtonRelease-1>', edit_player)
root.bind('<Return>', submit)
 

# start program
root.config(menu=menubar)
root.mainloop()

